﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SliderStyle
{
    public class MyVerifySlider : Slider
    {
        static MyVerifySlider()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(MyVerifySlider), new FrameworkPropertyMetadata(typeof(MyVerifySlider)));
        }

        public event Action OnVerify;

        public ICommand OnVerifyCommand
        {
            get { return (ICommand)GetValue(OnVerifyCommandProperty); }
            set { SetValue(OnVerifyCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for OnVerifyCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty OnVerifyCommandProperty =
            DependencyProperty.Register("OnVerifyCommand", typeof(ICommand), typeof(MyVerifySlider), new PropertyMetadata(null));

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(MyVerifySlider), new PropertyMetadata("按住滑块滑动，拖到最右边"));

        private Grid grid;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.grid = this.Template.FindName("shadeGrid", this) as Grid;
        }

        protected override void OnValueChanged(double oldValue, double newValue)
        {
            base.OnValueChanged(oldValue, newValue);

            if (this.grid != null)
            {
                this.grid.HorizontalAlignment = HorizontalAlignment.Right;
                this.grid.Width = (1 - (this.Value / this.Maximum)) * this.ActualWidth;
            }

            if (newValue == this.Maximum)
            {
                this.Text = "验证中";
                this.OnVerify?.Invoke();
                if (this.OnVerifyCommand != null && this.OnVerifyCommand.CanExecute(null))
                {
                    this.OnVerifyCommand.Execute(null);
                }
            }
        }
    }
}